package com.liufh.service.impl;

import com.liufh.common.ResultData;
import com.liufh.dao.AuthCodeDao;
import com.liufh.feign.EmailServiceFeignClient;
import com.liufh.pojo.AuthCode;
import com.liufh.service.CodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Random;

/**
 * @author: liufh
 * @create: 2022-01-25 16:52
 **/
@Service
public class CodeServiceImpl implements CodeService {

    @Autowired
    private AuthCodeDao authCodeDao;

    @Autowired
    private EmailServiceFeignClient emailServiceFeignClient;

    @Override
    public void createCode(String email) {
        // 生成验证码
        Random random = new Random();
        String code = "";
        for (int i = 0; i < 6; i++) {
            code += random.nextInt(10);
        }
        System.out.println("====code:" + code);

        // 保存
        AuthCode authCode = new AuthCode();
        authCode.setCode(code);
        authCode.setEmail(email);
        authCode.setCreatetime(new Date());
        authCodeDao.save(authCode);

        // 发送邮箱
        ResultData emailRes = emailServiceFeignClient.email(email, code);
        System.out.println(emailRes);
    }

    @Override
    public String validateCode(String email, String code) {
        AuthCode authCode = new AuthCode();
        authCode.setCode(code);
        authCode.setEmail(email);
        Example<AuthCode> example = Example.of(authCode);
        try {
            AuthCode authCodeRes = authCodeDao.findOne(example).get();
            return "0";
        } catch (Exception e) {
        }
        return null;
    }

}
